const regeneratorRuntime = require("../../utils/runtime.js")
const login = require('../../utils/utils.js')
const {
  _post,
  _get
} = require('../../utils/request.js')
const App = getApp()
Page({
  data: {
    statusHeight: wx.getSystemInfoSync().statusBarHeight || 0,
    loginShow: false,
    userInfo: wx.getStorageSync('userInfo') || {},
    defaultAvatar: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581442582138&di=8e8d9b61c871d74e803468ed1bd730e8&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F-fo3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fwh%3D450%2C600%2Fsign%3Da2063092a4cc7cd9fa783cdd0c310d09%2F09fa513d269759ee33c44bb4b5fb43166d22df3c.jpg'
  },

  async onLoad() {
    await this.checkLogin()
  },

  async checkLogin() {
    try {
      let res = await login.login()
      if (res.nickName) {
        App.state.isLogin = true
        await this.setToken(true)
        this.setData({
          loginShow: false,
          userInfo: res
        })
      }
    } catch (err) {
      App.state.isLogin = false
      this.setData({
        loginShow: true
      })
    }
  },

  async gotUserInfo(info) {
    if (info && info.detail && info.detail.userInfo) {
      wx.setStorageSync('userInfo', info.detail.userInfo)
      this.setData({
        userInfo: info.detail.userInfo
      })
      await this.setToken(true)
    }
  },

  async setToken(hasUserInfo) {
    if (!hasUserInfo) {
      await this.checkLogin()
    }
    let res = await _post('/wx', {
      code: wx.getStorageSync('loginCode').code,
      raw_data: JSON.stringify(wx.getStorageSync('userInfo'))
    })

    if (res.code === 0) {
      wx.setStorageSync('auth', res.data)
      this.setData({
        loginShow: false
      })
    } else {
      this.setData({
        loginShow: true
      })
    }
  }
})